package com.samnative.pineapple.adapter;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.samnative.pineapple.entity.ShoppingCarModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.instance.UserInfo;
import com.samnative.pineapple.main.R;
import com.samnative.pineapple.utils.GlideRequestOptions;
import com.samnative.pineapple.utils.ViewHelper;
import com.samnative.pineapple.widget.AddSubtractNumView;
import com.samnative.pineapple.widget.EditBuyNumPop;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Integer.parseInt;

/**
 * 购物车列表适配器
 *
 * @author WangPeng
 */
public class ShoppingCarAdapter extends BaseExpandableListAdapter {

    private Context context;
    private DecimalFormat df = new DecimalFormat("0.00");
    List<ShoppingCarModel> listData;
    private boolean isFinish = true;

    public ShoppingCarAdapter(Context context) {
        this.context = context;
        listData = UserInfo.getInstance().getListShoppingCar();
    }

    @Override
    public int getGroupCount() {
        // TODO Auto-generated method stub
        return listData.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        // TODO Auto-generated method stub
        return listData.get(groupPosition).getGoodsData().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        // TODO Auto-generated method stub
        return listData.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        return listData.get(groupPosition).getGoodsData().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        // TODO Auto-generated method stub
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        return childPosition;
    }

    public boolean isFinish() {
        return isFinish;
    }

    public void setFinish(boolean isFinish) {
        this.isFinish = isFinish;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHodlerGroup vhodlerGroup;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(
                    R.layout.item_shoppingcar_title, null);
            vhodlerGroup = new ViewHodlerGroup();
            vhodlerGroup.tvName = (TextView) convertView
                    .findViewById(R.id.tv_item_shoppingcar_group_title);
            vhodlerGroup.ivIsCheck = (ImageView) convertView
                    .findViewById(R.id.iv_item_shoppingcar_head_ischeck);
            vhodlerGroup.tv_item_shoppingcar_group_edit = (TextView) convertView
                    .findViewById(R.id.tv_item_shoppingcar_group_edit);
            convertView.setTag(vhodlerGroup);
        } else {
            vhodlerGroup = (ViewHodlerGroup) convertView.getTag();
        }

        final ShoppingCarModel model = listData.get(groupPosition);
        vhodlerGroup.tvName.setText(model.getBusinessname());

        // 判断店铺是否选中
        if (model.isChecked()) {
            vhodlerGroup.ivIsCheck
                    .setImageResource(R.mipmap.ic_check_pressed_toolbar);
        } else {
            vhodlerGroup.ivIsCheck
                    .setImageResource(R.mipmap.ic_check_toolbar);
        }

        // 选中店铺监听
        vhodlerGroup.ivIsCheck.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (onBuyItem != null) {
                    onBuyItem.checkedGroup(groupPosition);
                }
            }
        });

        // 进入店铺监听
        vhodlerGroup.tvName.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

//        if (isFinish) {
//            vhodlerGroup.tv_item_shoppingcar_group_edit.setText("编辑");
//        }
        // 开关编辑功能
        vhodlerGroup.tv_item_shoppingcar_group_edit
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if (model.isEdit() == true) {
                            // 关闭编辑功能
                            model.setEdit(false);
                            vhodlerGroup.tv_item_shoppingcar_group_edit
                                    .setText("编辑");
                            isFinish = true;
                        } else {
                            // 打开编辑功能
                            model.setEdit(true);
                            vhodlerGroup.tv_item_shoppingcar_group_edit
                                    .setText("完成");
                            isFinish = false;
                        }
                        notifyDataSetChanged();
                    }
                });

        boolean is = false;
        for (int i = 0; i < model.getGoodsData().size(); i++) {
            if (model.getGoodsData().get(i).getEnable().equals("1")) {
                is = true;
                break;
            }
        }
        if (is) {
            vhodlerGroup.ivIsCheck.setVisibility(View.VISIBLE);
        } else {
            vhodlerGroup.ivIsCheck.setVisibility(View.INVISIBLE);
        }

        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHodlerChild vHodlerChild = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(
                    R.layout.item_shoppingcar_content, null);
            vHodlerChild = new ViewHodlerChild();
            vHodlerChild.connect_layout = (RelativeLayout) convertView
                    .findViewById(R.id.connect_layout);
            vHodlerChild.rl_itemproinfo_edit = (RelativeLayout) convertView
                    .findViewById(R.id.rl_itemproinfo_edit);
            vHodlerChild.rl_itemproinfo = (RelativeLayout) convertView
                    .findViewById(R.id.rl_itemproinfo);
            vHodlerChild.connect_layout.setTag("");
            vHodlerChild.iv_itemproimg = (ImageView) convertView
                    .findViewById(R.id.iv_itemproimg);
            vHodlerChild.tv_proname = (TextView) convertView
                    .findViewById(R.id.tv_itemproname);
            vHodlerChild.tv_prospec = (TextView) convertView
                    .findViewById(R.id.tv_itemprospec);
            vHodlerChild.llBottom = (View) convertView
                    .findViewById(R.id.item_shopping_char_bottom);
            vHodlerChild.iv_ischeck = (ImageView) convertView
                    .findViewById(R.id.iv_ischeck);
            vHodlerChild.asnv = (AddSubtractNumView) convertView
                    .findViewById(R.id.asnv_item_buy);
            vHodlerChild.amount_tv = (TextView) convertView.findViewById(R.id.amount_tv);
            vHodlerChild.tv_itemcount = (TextView) convertView
                    .findViewById(R.id.tv_itemcount);
            vHodlerChild.tv_item_delete = (TextView) convertView
                    .findViewById(R.id.tv_item_delete);
            vHodlerChild.tv_spec_edit = (TextView) convertView
                    .findViewById(R.id.tv_spec_edit);
            vHodlerChild.tv_invalid = (TextView) convertView
                    .findViewById(R.id.tv_invalid);
            vHodlerChild.line = convertView.findViewById(R.id.line);
            convertView.setTag(vHodlerChild);
        } else {
            vHodlerChild = (ViewHodlerChild) convertView.getTag();
        }

        final ShoppingCarModel.GoodsData item = listData.get(groupPosition)
                .getGoodsData().get(childPosition);

        if (childPosition == listData.get(groupPosition).getGoodsData().size() - 1) {
            vHodlerChild.llBottom.setVisibility(View.VISIBLE);
            vHodlerChild.line.setVisibility(View.GONE);
        } else {
            vHodlerChild.llBottom.setVisibility(View.GONE);
            vHodlerChild.line.setVisibility(View.VISIBLE);
        }

        vHodlerChild.asnv.setMaxNum(item.getProductstorage());
        // vHodlerChild.asnv.setMinNum(parseInt(item.getF_leastnumber()));
        vHodlerChild.tv_itemcount.setText("X" + item.getProductnum());
        vHodlerChild.asnv.setNumDefault(parseInt(item.getProductnum()));
        // 监听数量变化
        vHodlerChild.asnv.setOnAsnwChecked(new AddSubtractNumView.OnAsnwChecked() {
            @Override
            public void getNum(int num) {
                // TODO Auto-generated method stub

//                listData.get(groupPosition).getGoodsData().get(childPosition)
//                        .setProductnum(num + "");
//                notifyDataSetChanged();
                requestUpNum(
                        listData.get(groupPosition).getGoodsData()
                                .get(childPosition), num + "");

            }
        });

        // 判断商品是否选中
        if (item.isChecked()) {
            vHodlerChild.iv_ischeck
                    .setImageResource(R.mipmap.ic_check_pressed_toolbar);
        } else {
            vHodlerChild.iv_ischeck
                    .setImageResource(R.mipmap.ic_check_toolbar);
        }

        vHodlerChild.tv_proname.setText(item.getProductname());
        vHodlerChild.tv_prospec.setText(item.getSpec());
        vHodlerChild.tv_spec_edit.setText(item.getSpec());
        double price = item.getProuctprice();
        double bull = item.getBullamount();
        if (price > 0 && bull > 0) {
            vHodlerChild.amount_tv.setText("¥" + df.format(price) + " + " + df.format(bull) + "积分");
        } else if (price > 0 && bull == 0) {
            vHodlerChild.amount_tv.setText("¥" + df.format(price));
        } else {
            vHodlerChild.amount_tv.setText(df.format(bull) + "积分");
        }

        // 判断商品的状态
        if (item.getEnable().equals("1")) {
            vHodlerChild.iv_ischeck.setVisibility(View.VISIBLE);
            vHodlerChild.tv_invalid.setVisibility(View.GONE);
            vHodlerChild.connect_layout.setAlpha(1.0f);
            vHodlerChild.asnv.setVisibility(View.VISIBLE);
        } else {
            vHodlerChild.iv_ischeck.setVisibility(View.GONE);
            vHodlerChild.connect_layout.setAlpha(0.6f);
            vHodlerChild.asnv.setVisibility(View.GONE);
            vHodlerChild.tv_invalid.setVisibility(View.VISIBLE);
            // switch (item.getF_code_status()) {
            // case 1:// 失效
            // vHodlerChild.tv_invalid
            // .setImageResource(R.drawable.shopping_state_invalid_1);
            // vHodlerChild.tv_proprice
            // .setText("￥" + (item.getF_show_price()));
            // break;
            // case 2:// 缺货
            // vHodlerChild.tv_invalid
            // .setImageResource(R.drawable.shopping_state_lack_1);
            // vHodlerChild.tv_proprice
            // .setText("￥" + (item.getF_show_price()));
            // break;
            // case 3:// 售罄
            // vHodlerChild.tv_invalid
            // .setImageResource(R.drawable.shopping_state_end_1);
            // vHodlerChild.tv_hd_xg.setVisibility(View.GONE);
            // vHodlerChild.tv_proprice
            // .setText("￥" + (item.getF_show_price()));
            // break;
            // }
        }

        // 选中店铺监听
        vHodlerChild.iv_ischeck.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (onBuyItem != null) {
                    onBuyItem.checkedChild(groupPosition, childPosition);
                }
            }
        });

        // 商品长按监听
        vHodlerChild.connect_layout
                .setOnLongClickListener(new OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        // TODO Auto-generated method stub
                        if (onBuyItem != null) {
                            onBuyItem.deleteProduct(groupPosition,
                                    childPosition);
                        }
                        return false;
                    }
                });

        // 商品点击监听
        vHodlerChild.connect_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (listData.get(groupPosition).isEdit()) {
                    return;
                }
//                Intent intent = new Intent(context, ProductDetailActivity.class);
//                intent.putExtra("productId", item.getProductid() + "");
//                context.startActivity(intent);
            }
        });

        // try {
        // // 设置输入购买数量
        // vHodlerChild.asnv.setOnClickListener(new Click(item,
        // vHodlerChild.asnv.getNum(), parseInt(item
        // .getF_productstorage()), parseInt(item
        // .getF_leastnumber())));
        // } catch (Exception e) {
        // e.printStackTrace();
        // }

        // 是否显示编辑状态
        if (listData.get(groupPosition).isEdit()) {
            vHodlerChild.rl_itemproinfo.setVisibility(View.GONE);
            vHodlerChild.rl_itemproinfo_edit.setVisibility(View.VISIBLE);
        } else {
            vHodlerChild.rl_itemproinfo.setVisibility(View.VISIBLE);
            vHodlerChild.rl_itemproinfo_edit.setVisibility(View.GONE);
        }

        vHodlerChild.tv_item_delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (onBuyItem != null) {
                    onBuyItem.deleteProduct(groupPosition, childPosition);
                }
            }
        });

        vHodlerChild.tv_spec_edit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (onBuyItem != null) {
                    onBuyItem.editSpec(groupPosition, childPosition);
                }
            }
        });

        Glide.with(context)
                .load(item.getProductimage()) //图片地址
                .apply(GlideRequestOptions.OPTIONS_400_400)
                .into(vHodlerChild.iv_itemproimg);

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean hasStableIds() {
        // TODO Auto-generated method stub
        return false;
    }

    class ViewHodlerGroup {
        private TextView tvName;
        private ImageView ivIsCheck;
        private TextView tv_item_shoppingcar_group_edit;
    }

    class ViewHodlerChild {
        private ImageView iv_itemproimg, iv_ischeck;
        private TextView tv_proname, tv_prospec, amount_tv,
                tv_invalid, tv_itemcount, tv_item_delete,
                tv_spec_edit;
        private RelativeLayout connect_layout, rl_itemproinfo,
                rl_itemproinfo_edit;
        private AddSubtractNumView asnv;
        private View llBottom, line;
        ;
    }

    public class Click implements OnClickListener {

        private ShoppingCarModel.GoodsData item;

        /**
         * 最大库存量
         */
        private int maxBuyNum;
        /**
         * 起购数
         */
        private int minBuyNum;
        /**
         * 当前数量
         */
        private int currentNum = 1;

        public Click(ShoppingCarModel.GoodsData item, int currentNum,
                     int maxBuyNum, int minBuyNum) {
            super();
            this.item = item;
            this.maxBuyNum = maxBuyNum;
            this.currentNum = currentNum;
            this.minBuyNum = minBuyNum;

        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            switch (v.getId()) {
                case R.id.asnv_item_buy:
                    if (minBuyNum > maxBuyNum) {
                        ToastUtils.showShort("暂不支持输入修改");
                        item.setProductnum(maxBuyNum + "");
                        return;
                    }
                    EditBuyNumPop pop = new EditBuyNumPop(context);
                    WindowManager.LayoutParams params = pop.getWindow()
                            .getAttributes();
                    params.width = (int) (ViewHelper.getWindowRealize((Activity) context).x * 0.65);
                    pop.getWindow().setAttributes(params);
                    pop.setNumView(item);
                    pop.setMaxBuyNum(maxBuyNum);
                    pop.setCurrentNum(currentNum);
                    pop.setMinBuyNum(minBuyNum);
                    pop.setOnResult(new EditBuyNumPop.OnResult() {
                        @Override
                        public void ok(int num) {
                            // TODO Auto-generated method stub
//                            notifyDataSetChanged();
                            requestUpNum(item, item.getProductnum());
                        }
                    });
                    pop.show();
                    break;
                default:
                    break;
            }

        }

    }

    public OnBuyItem onBuyItem;

    public void setOnBuyItem(OnBuyItem onBuyItem) {
        this.onBuyItem = onBuyItem;
    }

    public interface OnBuyItem {

        /**
         * 数量变化
         */
        public void upNum();

        /**
         * 选中店铺
         */
        public void checkedGroup(int groupPosition);

        /**
         * 选中商品
         */
        public void checkedChild(int groupPosition, int childPosition);

        /**
         * 删除商品
         */
        public void deleteProduct(int groupPosition, int childPosition);

        /**
         * 编辑规格
         */
        public void editSpec(int groupPosition, int childPosition);
    }

    /**
     * 请求修改购物车商品数量
     */
    public void requestUpNum(final ShoppingCarModel.GoodsData goodsData, final String num) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mtoken", AppPrefer.getInstance(context).getString(AppPrefer.mtoken, ""));
        map.put("cartid", goodsData.getCartid() + "");
        map.put("num", num + "");
        map.put("_apiname", "shopingcart.index.updateCartNum");
        HttpRequest.post((Activity) context, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                goodsData.setProductnum(num + "");
                if (onBuyItem != null) {
                    onBuyItem.upNum();
                }
            }

            @Override
            public void requestFinish() {
                super.requestFinish();
                notifyDataSetChanged();
            }
        });
    }
}
